require "RadioMenu"

RenWuScene={}
RenWuSceneFunc={}
RenWuSceneFunc.__index = RenWuSceneFunc
setmetatable(RenWuScene, RenWuSceneFunc)
RenWuScene.NodeID = {Menu=1001, CloseButton=1002, GainExpLabel=1004, GainCashLabel=1005, DescLabel=1006}
local RenWuItemID = {NameLabel=1001, DescLabel=1002}
local RenWuDesc = {mainline=""}

RenWuSceneFunc.getNode = function()
  local l = {}
  setmetatable(l, RenWuSceneFunc)
  l.node = CCBReader:load("RenWuScene.ccbi")
  print("RenWuScene.getNode", l.node)
  RenWuScene.instance = l
  l:init() 
  return l 
end

RenWuSceneFunc.getScene = function()
  local sc = CCScene:create()
  sc:addChild(RenWuScene:getNode().node)  
  print("RenWuScene.getScene", sc)
  return sc
end

RenWuSceneFunc.init = function(self)
  setObjectExtTable(self.node:getChildByTag(RenWuScene.NodeID.CloseButton), self)
  setObjectExtTable(self.node:getChildByTag(1020), self)
  setObjectExtTable(self.node:getChildByTag(1021), self)
  setObjectExtTable(self.node:getChildByTag(1111), self)

  if self.menu~=nil then
    self.node:removeChild(self.menu, true)
  end
  self.menu = self:createMenu() 
  self.node:addChild(self.menu)

  self.radioMenu = RadioMenu:create(self.menu, "menuItemChanged", self)
  self.radioMenu:setMenuState(0)
  
  self.currentRenWuType = self.renWuItems:at(0).renwuType
  self.currentRenWuID = self.renWuItems:at(0).rid
  --self:createRenWuItem()
  print("####", self, RenWuScene.instance, RenWuScene.instance.curGoButtons, self.curGoButtons)
  for k,v in pairs(RenWuScene.instance.curGoButtons) do
    print("--", k, v)
  end
  RenWuGuide.nextStep()
end
RenWuSceneFunc.getQuestInfo = function(self, rid)
  for k,v in pairs(UserData.userinfo.quests) do
    --print("RenWuSceneFunc.getQuestInfo", rid, k, v.actionItem)
    if v.id==rid then
      return v
    end
  end
  return nil
end

RenWuSceneFunc.checkRenWuComplete = function(self, rid)
  for k,v in pairs(self.renWuItems.data) do
    print("RenWuSceneFunc.checkRenWuComplete", self.renWuItems, #self.renWuItems, k, v.rid)
    local quest = self:getQuestInfo(v.rid)
    local qs = quest.questIds
    local questItems = {}
    if #qs==0 then
      questItems[#questItems+1] = v.rid
    else
      for k,v in pairs(qs) do
        questItems[#questItems+1] = v 
      end
    end
    local flag = true
    for k1, v1 in pairs(questItems) do
      local quest = self:getQuestInfo(v1)
      if quest~=nil then
        local total = 0
        if quest.threshold~=nil then total=quest.threshold;end
        local cur = 0
        local tmp = UserData.userinfo.host.currentQuests[tostring(v1)]
        if tmp~=nil then cur=tmp;end
        print("RenWuSceneFunc.checkRenWuComplete", total, cur) 
        if total>0 and total>cur then
          flag = false
        end
      end
    end
    if flag==true then
      print("RenWuSceneFunc.checkRenWuComplete yes")
      return true
    end
  end
  print("RenWuSceneFunc.checkRenWuComplete no")
  return false
end

RenWuSceneFunc.createItemLayer = function(self, imgName, t, rid)
  local q = Quest:create(rid)

  local l = CCSprite:create()
  local sp = CCSprite:create(imgName)
  sp:setScale(1.6)
  sp:setAnchorPoint(ccp(0,0))
  --sp:setPosition(ccp(168,40))
  l:addChild(sp)
  local dotName = ""
  if q:checkComplete()==true then
    dotName = "greenlight.png"
  else
    dotName = "yellowlight.png"
  end
  local dotSP = CCSprite:create(dotName)
  l:addChild(dotSP)
  dotSP:setPosition(ccp(30,64))
  local tmp = "主线"
  if t=="otherline1" or t=="otherline2" then 
    tmp = "支线"; 
  elseif t=="bounty" then
    tmp = "酒馆"
  end 
  local lb = CCLabelTTF:create(tmp, "Helvetica", 28)
  l:addChild(lb)
  lb:setPosition(ccp(72,58))
  print("RenWuSceneFunc.createItemLayer", rid)
  --local quest = UserData.userinfo.quests[tostring(rid)]
  local quest = self:getQuestInfo(rid) 
  lb = CCLabelTTF:create(quest.title, "Helvetica", 28)
  l:addChild(lb)
  lb:setPosition(ccp(230,38))
  
  local size = sp:getContentSize()
  local scale = sp:getScale() 
  l:setContentSize(CCSizeMake(size.width*scale, size.height*scale))
  local size = l:getContentSize()
  print("RenWuScene.createItemLayer", size.width, size.height)
  return l
end
RenWuSceneFunc.createMenuItem = function(self, t, rid)
  local l1 = self:createItemLayer("renwu_normal.png", t, rid)
  local l2 = self:createItemLayer("renwu_selected_up.png", t, rid)
  local l3 = self:createItemLayer("renwu_normal.png", t, rid)
  return CCMenuItemSprite:create(l1, l2, l3)
end

RenWuSceneFunc.createMenu = function(self)
  local menu = CCMenu:create()
  local i=0
  self.renWuItems = Array:create()
  self.oldQuests = {}
  for k,v in pairs(UserData.userinfo.curQuests) do
    --local quest = UserData.userinfo.quests[tostring(v)]
    local quest = self:getQuestInfo(v) 
    if v~=0 and quest~=nil then
      print("RenWuSceneFunc.createMenu", quest.actionItem)
      self.oldQuests[v] = quest
      local item = self:createMenuItem(k,v)
      addMenuItemHandler(item, "onSelectMenuItem")
      --item:registerScriptTapHandler(onSelectRenWuItem)
      menu:addChild(item)
      item:setPosition(ccp(0, 490-i*100))
      i = i+1
      item:setTag(self.renWuItems:size())
      self.renWuItems:append({menuItem=item, renwuType=k, rid=v})
    end
  end
  
  
  for k,v in pairs(UserData.userinfo.host.currentQuests) do
    local quest = self:getQuestInfo(tonumber(k))
    if quest.type == "bounty" then
      local item = self:createMenuItem("bounty", quest.id)
      addMenuItemHandler(item, "onSelectMenuItem")
      menu:addChild(item)
      item:setPosition(ccp(0, 490-i*100))
      i = i+1
      item:setTag(self.renWuItems:size())
      self.renWuItems:append({menuItem=item, renwuType="bounty", rid=quest.id})
    end
  end
  --for k, v in pairs(self.renWuItems.data) do
  --  print("#--##", k, v.rid)
  --end
  --self.node:addChild(menu)
  menu:setPosition(ccp(205, 0))
  return menu
end

RenWuSceneFunc.setRenWuReward = function(self)
  local rewardLayer = self.node:getChildByTag(2001)
  for i=1,5 do
    rewardLayer:getChildByTag(i):setVisible(false)
  end
  if self.rewardItems~=nil then
    for k,v in pairs(self.rewardItems) do
      rewardLayer:removeChild(v, true)    
    end
  end
  self.rewardItems = {} 
  local quest = self:getQuestInfo(self.currentRenWuID)
  local xp = quest.xpReward
  local cash = quest.cashReward
  if quest.type=="bounty" then
    local info = nil
    for k,v in pairs(UserData.userinfo.host.store.bounty.b) do
      if v.q == self.currentRenWuID then info=v end
    end
    if info~=nil then
      xp = JiuGuanScene.ColorRate[info.s]*Player.getLevelData().bountyXp
      cash = JiuGuanScene.ColorRate[info.s]*Player.getLevelData().bountyCash
    end
  end
  local l = createItemLayer({type="xp", id=0, num=xp})
  addLayerFromBK(rewardLayer, 1, l)
  rewardLayer:getChildByTag(1):setVisible(true)
  self.rewardItems[#self.rewardItems+1] = l
  
  l = createItemLayer({type="cash", id=0, num=cash})
  addLayerFromBK(rewardLayer, 2, l)
  rewardLayer:getChildByTag(2):setVisible(true)
  self.rewardItems[#self.rewardItems+1] = l
  
  for k,v in ipairs(quest.reward) do
    l = createItemLayer(v)
    addLayerFromBK(rewardLayer, 2+k, l)
    rewardLayer:getChildByTag(2+k):setVisible(true)
    self.rewardItems[#self.rewardItems+1] = l
  end 
end

RenWuSceneFunc.createRenWuItem = function(self)
  self:setRenWuReward()
  local questItems = Array:create()
  --local quest = UserData.userinfo.quests[tostring(self.currentRenWuID)]
  local quest = self:getQuestInfo(self.currentRenWuID) 
  print("RenWuSceneFunc.createRenWuItem", self.currentRenWuID, quest.type)
   
  local label = self.node:getChildByTag(RenWuScene.NodeID.DescLabel)
  local p1,p2 = string.find(quest.desc, "<br>")
  local desc = quest.desc
  if p1~=nil then
    desc = string.sub(quest.desc, 0, p1-1)
  end
  TypeCast(label, "CCLabelTTF"):setString(autoEnter(desc, 78))
  
  local xp = quest.xpReward
  local cash = quest.cashReward
  if quest.type=="bounty" then
    local info = nil
    for k,v in pairs(UserData.userinfo.host.store.bounty.b) do
      if v.q == self.currentRenWuID then info=v end 
    end
    if info~=nil then 
      print("RenWuSceneFunc.createRenWuItem", self.currentRenWuID, quest.type, info.s)
      xp = JiuGuanScene.ColorRate[info.s]*Player.getLevelData().bountyXp
      cash = JiuGuanScene.ColorRate[info.s]*Player.getLevelData().bountyCash
    end
    local b = TypeCast(self.node:getChildByTag(1021), "CCButton")
    b:setEnabled(true)
    b:setVisible(true)
  else
    local b = TypeCast(self.node:getChildByTag(1021), "CCButton")
    b:setEnabled(false)
    b:setVisible(false)
  end
  --[[
  label = self.node:getChildByTag(RenWuScene.NodeID.GainExpLabel)
  TypeCast(label, "CCLabelTTF"):setString(tostring(xp))
  label = self.node:getChildByTag(RenWuScene.NodeID.GainCashLabel)
  TypeCast(label, "CCLabelTTF"):setString(tostring(cash))
  ]]
  --子任务列表
  --print("RenWuSceneFunc.createRenWuItem", quest.questIds)
  local qs = quest.questIds--cjson.decode(quest.questIds)
  if #qs==0 then
    --questItems:append(UserData.userinfo.curQuests[self.currentRenWuType]) 
    questItems:append(self.currentRenWuID) 
  else
    for k,v in pairs(qs) do
      questItems:append(v)
    end
  end
  if self.currentRenWuList~=nil then
    for i=0,self.currentRenWuList:size()-1 do
      self.node:removeChild(self.currentRenWuList:at(i), true)
    end
  end
  self.currentRenWuList = Array:create()
  self.curGoButtons = {}
  local isCompleted = true
  for i=0,questItems:size()-1 do
    --local quest = UserData.userinfo.quests[tostring(questItems:at(i))]
    local quest = self:getQuestInfo(questItems:at(i)) 
    if quest~=nil then
      print("RenWuScene.createRenWuItem", questItems:at(i), quest.actionItem)
      local item = CCBReader:load("RenWuItem.ccbi")
      local label = item:getChildByTag(RenWuItemID.NameLabel)
      TypeCast(label, "CCLabelTTF"):setString(quest.actionItem)
      label = item:getChildByTag(RenWuItemID.DescLabel)
      local total = 0
      if quest.threshold~=nil then total=quest.threshold;end
      local cur = 0
      local tmp = UserData.userinfo.host.currentQuests[tostring(questItems:at(i))]
      if tmp~=nil then cur=tmp;end
      TypeCast(label, "CCLabelTTF"):setString(string.format("%d/%d", cur, total))
      if total>cur then isCompleted=false end
 
      setObjectExtTable(item:getChildByTag(1020), self)
      self.curGoButtons[#self.curGoButtons+1] = item:getChildByTag(1020) 
      item:getChildByTag(1020):setTag(quest.id)
      self.node:addChild(item)
      item:setPosition(400, 450-40*i)
      self.currentRenWuList:append(item)
    end
  end
  --local b = TypeCast(self.node:getChildByTag(1020), "CCButton")
  --b:setEnabled(isCompleted) 
end

RenWuSceneFunc.acceptNextRenWu = function(self)
  --local quest = UserData.userinfo.quests[tostring(self.currentRenWuID)]
  local quest = self:getQuestInfo(self.currentRenWuID) 
  NetworkRequest.acceptQuest(quest.nextQuest)
  self:init()
end
--[[
RenWuScene.acceptNextRenWuSucced = function()
  local quest = UserData.quests[tostring(RenWuScene.currentRenWuID)]
  UserData.userinfo.curQuests[renwuType] = quest.nextQuest 
  RenWuScene.init() 
end
]]
RenWuSceneFunc.menuItemChanged = function(self, oldIndex, newIndex)
  self.currentRenWuType = self.renWuItems:at(newIndex).renwuType 
  self.currentRenWuID = self.renWuItems:at(newIndex).rid
  print("RenWuSceneFunc.menuItemChanged", oldIndex, newIndex, self.currentRenWuType, self.currentRenWuID)
  self:createRenWuItem()
end

RenWuSceneFunc.onGiveUpRenWuButton = function(self, node)
  NetworkRequest.giveUpQuest(self.currentRenWuID, "onGiveUpRenWuComplete", self)
end
RenWuSceneFunc.onGiveUpRenWuComplete = function(self, data)
  print("RenWuSceneFunc.onGiveUpRenWuComplete", data)
  local res = cjson.decode(data)
  if res.ret==0 then
    NetworkRequest.syncData(res)
    self:init()
  else
    showMessage(res.msg, ccc3(255,0,0))
  end
end
RenWuSceneFunc.onCompleteRenWuButton = function(self, node)
  NetworkRequest.completeQuest(self.currentRenWuID, "onCompleteRenWuComplete", self)
  --setTouchEnabledAll(self.node, false)
  LoadScene:showLoadingScene()
end
RenWuSceneFunc.onCompleteRenWuComplete = function(self, data)
  print("RenWuSceneFunc.onCompleteRenWuComplete", data)
  --setTouchEnabledAll(self.node, true)
  --LoadScene:removeLoadingScene()
  local res = cjson.decode(data)
  if res.ret==0 then
    NetworkRequest.syncData(res)
    showMessage("任务完成", ccc3(0,255,0))
    --UserData.userinfo.curQuests = res.curQuests
    --UserData.userinfo.quests = res.quests
    --local ma = CCMoveTo:create(0.5, ccp(20, 640))
    --local ac = ActionUtil.createSeqAction({ma, CCCallFuncN:create(YuanZhenShopSceneFunc.onActionDone)})
    --sp:runAction(ac)
 
    --local quest = UserData.userinfo.quests[tostring(self.currentRenWuID)]
    local quest = self:getQuestInfo(self.currentRenWuID) 
    if quest.type~="bounty" then
      --self:init()
      self.newQuests = {}
      for k,v in pairs(res.curQuests) do
        local quest = self:getQuestInfo(v)
        if v~=0 and quest~=nil and self.oldQuests[v]==nil then
          self.newQuests[v] = quest
        end
      end
      --[[
      for k,v in pairs(self.newQuests) do
        print("##### new quests", k, v)
      end
      for k,v in pairs(self.oldQuests) do
        print("##### old quests", k, v)
      end
      ]]
      self:checkAcceptQuest() 
     --NetworkRequest.acceptQuest(quest.nextQuest, "onAcceptQuestComplete", self)
    else
      --setTouchEnabledAll(self.node, true)
      LoadScene:removeLoadingScene()
      self:init()
    end
  else
    --setTouchEnabledAll(self.node, true)
    LoadScene:removeLoadingScene()
    showMessage(res.msg, ccc3(255,0,0))
    RenWuGuide.nextStep()
  end
end
RenWuSceneFunc.checkAcceptQuest = function(self)
  local key = nil
  for k,v in pairs(self.newQuests) do
    key = k
    NetworkRequest.acceptQuest(k, "onAcceptQuestComplete", self)
    break
  end
  if key~=nil then
    self.newQuests[key]=nil
    return true
  end
  return false
end

RenWuSceneFunc.onAcceptQuestComplete = function(self, data)
  print("RenWuSceneFunc.onAcceptQuestComplete", data) 
  local res = cjson.decode(data)
  if res.ret==0 and res.data.result==true then
    NetworkRequest.syncData(res)
    --UserData.userinfo.curQuests = res.curQuests
    showMessage("接受到新任务", ccc3(0,255,0))
  else
    showMessage(res.msg, ccc3(255,0,0))
  end
  local flag = self:checkAcceptQuest()
  if flag==false then
    self:init()
    LoadScene:removeLoadingScene()
    RenWuGuide.nextStep()
  end
  --setTouchEnabledAll(self.node, true)
end

RenWuSceneFunc.onGoButton = function(self,node,event)
  local rid = node:getTag()
  print("RenWuSceneFunc.onGoButton", rid)
  local quest = self:getQuestInfo(rid)
  local l = self:locateQeust(quest)
  if l~=nil then
    MainScene.scene:removeChild(self.node, true)
    --MainScene.setState()
    --setTouchEnabledAll(MainScene.node, false)
    RenWuScene.instance = nil
    MainScene.scene:addChild(l.node)
  end
end

RenWuSceneFunc.onCloseRenWuScene = function(self,node)
  print("onCloseRenWuScene")
  MainScene.scene:removeChild(node:getParent(), true)
  setTouchEnabledAll(MainScene.node, true)
  MainScene.setState()
  RenWuScene.instance = nil
end


RenWuSceneFunc.locateQeust = function(self, quest)
  print("RenWuSceneFunc.locateQeust", quest, quest.action, quest.target)
  if quest.action == "checkpoint" then
    local c = UserData.config.models.Checkpoint[quest.target]
    local s = UserData.config.models.Stronghold[c.strongholdId]
    --local l = ZhanDouScene:getNode(c.strongholdId, c.id-s.firstCheckpoint+1)
    local l = ZhanDouScene:getNode(c.strongholdId, 1)
    --l:setStrongholdFocus(c.strongholdId)
    --l:setCheckpointFocus(c.id-s.firstCheckpoint+1)
    --MainScene.scene:addChild(l.node)
    RenWuGuide.nextStep()
    return l
  elseif quest.action == "harvestTown" then
    return ZhiHuiBuScene:getNode()
    --MainScene.scene:addChild(ZhiHuiBuScene:getNode().node)
  elseif quest.action == "createDecoration" then
    return ShouXunScene1:getNode()
    --MainScene.scene:addChild(ShouXunScene1:getNode().node)
  elseif quest.action == "harvestTrain" then
    return XunLianYingScene:getNode()
    --MainScene.scene:addChild(XunLianYingScene:getNode().node)
  elseif quest.action == "tech" or quest.action == "techC" then
    return KeXueYuanScene:getNode()
    --MainScene.scene:addChild(KeXueYuanScene:getNode().node)
  elseif quest.action == "strengthen" then
    local l = ZhuangBeiScene:getNode()
    l.radioMenu:setMenuState(1)
    return l
    --return ZhuangBeiScene:getNode()
    --MainScene.scene:addChild(ZhuangBeiScene:getNode().node)
  elseif quest.action == "foster" then
    return ZhuangBeiScene:getNode()
    --MainScene.scene:addChild(ZhuangBeiScene:getNode().node)
  elseif quest.action == "costCoin" then
  elseif quest.action == "accelerate" then
  elseif quest.action == "decorate" then
    return ShouXunScene1:getNode()
    --MainScene.scene:addChild(ShouXunScene1:getNode().node)
  elseif quest.action == "help" then
  elseif quest.action == "occupy" or quest.action == "occupyF" then
    return ZhanFuYingScene:getNode()
    --MainScene.scene:addChild(ZhanFuYingScene1:getNode().node)
  elseif quest.action == "rescue" then
  elseif quest.action == "upBuild" then
    if(quest.target == 1001) then
      return ZhiHuiBuScene:getNode()
      --MainScene.scene:addChild(ZhiHuiBuScene:getNode().node)
    elseif (quest.target == 1003) then
      return KeXueYuanScene:getNode()
      --MainScene.scene:addChild(KeXueYuanScene:getNode().node)
    elseif (quest.target == 1004) then
      return ZhanFuYingScene:getNode()
      --MainScene.scene:addChild(ZhanFuYingScene:getNode().node)
    elseif (quest.target == 1005) then
      return XunLianYingScene:getNode()
      --MainScene.scene:addChild(XunLianYingScene:getNode().node)
    elseif (quest.target == 1006) then
      return YinHangScene:getNode()
      --MainScene.scene:addChild(YinHangScene:getNode().node)
    elseif (quest.target == 1007) then
      return JunYingScene:getNode()
      --MainScene.scene:addChild(JunYingScene:getNode().node)
    end
  elseif quest.action == "recruit" then
    --return XunLianYingScene:getNode()
    local l = JunXiaoScene:getNode()
    l.radioMenu:setMenuState(1)
    return l
    --return JunXiaoScene:getNode()
    --MainScene.scene:addChild(XunLianYingScene:getNode().node)
  elseif quest.action == "athletics" then
    return JingJiChangScene:getNode()
    --MainScene.scene:addChild(JingJiChangScene:getNode().node)
  elseif quest.action == "conquer" then
    return YuanZhenScene:getNode()
    --MainScene.scene:addChild(YuanZhenScene:getNode().node)
  elseif quest.action == "formationC" then
    local l = JunXiaoScene:getNode()
    l.radioMenu:setMenuState(2)
    return l
    --MainScene.scene:addChild(JunXiaoScene:getNode().node)
  elseif quest.action == "generalEquipC" then
    return ZhuangBeiScene:getNode()
    --MainScene.scene:addChild(ZhuangBeiScene:getNode().node)
  elseif quest.action == "postBounty" then
  elseif quest.action == "refreshGeneral" then
  elseif quest.action == "useItem" then
  elseif quest.action == "qqAlarm" then
  elseif quest.action == "strengthenC" then
    local l = ZhuangBeiScene:getNode()
    l.radioMenu:setMenuState(1)
    return l
    --MainScene.scene:addChild(ZhuangBeiScene:getNode().node)
  elseif quest.action == "invite" then
    return FriendScene:getNode()
    --MainScene.scene:addChild(FriendScene:getNode().node)
  elseif quest.action == "upStone" then
    return ZhuangBeiScene:getNode()
    --MainScene.scene:addChild(ZhuangBeiScene:getNode().node)
  elseif quest.action == "exchangeCash" then
  elseif quest.action == "exchangePower" then
  end
  return nil
end
